<script setup>
import { ref, onMounted, computed } from 'vue'
import PageContainer from '@/components/pageContainer.vue'
import { submitAdminInfoService, getAdminInfoService } from '@/apis/center'
import { useUserStore } from '@/stores/user'
const UserStore = useUserStore()

// 获取表单
const formRef = ref(null)

// 管理员个人信息
const formModel = ref({
  avatar: '',
  phone: '',
  email: ''
})

// 管理员名字，管理员ID存入表单
const username = UserStore.UserList.username
formModel.value.id = UserStore.UserList.id

const rules = {
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    {
      pattern:
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: '请输入正确的邮箱',
      trigger: 'blur'
    }
  ]
}

// 获取管理员个人信息
const getAdminInfo = async () => {
  const res = await getAdminInfoService(formModel.value.id)
  formModel.value = res.data
}

// 提交管理员个人信息
const submitUserInfo = async () => {
  await formRef.value.validate()
  // 提交用户个人信息
  await submitAdminInfoService(formModel.value)
  ElMessage.success('保存成功！')
  UserStore.UserList.avatar = formModel.value.avatar
  getAdminInfo()
}

onMounted(() => {
  getAdminInfo()
})

// 上传管理员头像
// 头像上传路径URL
const uploadUrl = computed(() => {
  return `https://www.u2051641.nyat.app:64347/api/admin/avatar/upload`
})

// 图片上传前添加请求头
const token = computed(() => UserStore.UserList.token)
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${token.value}`
}))

// 图片上传前的操作
const beforeAvatarUpload = () => {
  if (!token.value) {
    ElMessage.error('请先登录或获取token')
    return false
  }
  return true
}

// 图片上传成功时的操作
const handleAvatarSuccess = async (response) => {
  formModel.value.avatar = response.url
  ElMessage.success('头像上传成功')
}
// 图片上传失败时的操作
const handleAvatarError = (error) => {
  ElMessage.error('头像上传失败', error.message)
}
</script>

<template>
  <PageContainer title="基本资料">
    <el-row :gutter="20" justify="center">
      <el-col :span="12">
        <el-form
          class="form"
          autocomplete="off"
          size="large"
          ref="formRef"
          label-width="200px"
          :rules="rules"
          :model="formModel"
        >
          <el-col :offset="4">
            <el-form-item>
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
              >
                <template #default>
                  <el-avatar
                    style="width: 100px; height: 100px"
                    :src="formModel.avatar"
                  >
                    <el-icon class="icon">
                      <i-ep-Avatar></i-ep-Avatar>
                    </el-icon>
                  </el-avatar>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-form-item label="用户名">
            <el-input disabled v-model="username"></el-input>
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="formModel.phone"
              placeholder="请输入联系电话"
            ></el-input>
          </el-form-item>

          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model="formModel.email"
              placeholder="请输入电子邮箱"
            ></el-input>
          </el-form-item>

          <el-col :offset="21">
            <el-button type="primary" @click="submitUserInfo">保存</el-button>
          </el-col>
        </el-form>
      </el-col>
    </el-row>
  </PageContainer>
</template>

<style lang="scss" scoped>
.form {
  height: 650px;
  max-width: 600px;

  .avatar-uploader {
    .icon {
      font-size: 45px;
    }
  }
}
</style>
